package com.example.srm.dict.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.srm.auth.anno.Authority;
import com.example.srm.common.controller.BaseController;
import com.example.srm.constant.DataDictionaryConstant;
import com.example.srm.constant.DataDictionaryTypeConstant;
import com.example.srm.constant.PermissionConstant;
import com.example.srm.dict.service.TDataDictionaryService;
import com.example.srm.domain.TDataDictionary;
import com.example.srm.domain.TDataDictionaryType;
import com.example.srm.dict.service.TDataDictionaryTypeService;
import com.example.srm.domain.vo.PageView;
import com.example.srm.domain.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @author pfk
 * @creatTime 2021/11/29 10:16
 * @describe    字典类型
 */
@Slf4j
@RestController
@RequestMapping("dict_type")
@CrossOrigin
public class DataDictionaryTypeController extends BaseController<TDataDictionaryTypeService, TDataDictionaryType> {
    @Autowired
    private TDataDictionaryTypeService service;
    @Autowired
    private TDataDictionaryService dictionaryService;


    /**
     * 查询
     */
    @RequestMapping(value = "/query1",method = RequestMethod.GET)
    public Result query(Integer page, Integer pageSize, String code){
        //校验参数是否合法
        if (page==null||page<0){
            page=1;
        }
        if (pageSize==null||pageSize<=0){
            pageSize=10;
        }

        Page<TDataDictionaryType> tPage;
        if (code!=null){
            tPage = service.page(new Page<>(page,pageSize),new QueryWrapper<TDataDictionaryType>().eq(DataDictionaryTypeConstant.code,code));
        }else {
            tPage = service.page(new Page<>(page,pageSize));
        }
        //获取类别
        TDataDictionaryType type = tPage.getRecords().get(0);
        //根据类别查询类别明细
        HashMap<String, Object> map = new HashMap<>();
        map.put(DataDictionaryConstant.typeId,type.getId());
        List<TDataDictionary> dictionaryList = dictionaryService.listByMap(map);
        //绑定类别明细
        type.setDataDictDetails(dictionaryList);

        PageView<TDataDictionaryType> pageView = new PageView<TDataDictionaryType>()
                .setRows(Arrays.asList(type))
                .setTotalCount(tPage.getTotal())
                .setTotalPage(new Integer(tPage.getPages()+""));

        return new Result().setData(pageView).setSuccess(true);

    }

    @Override
    @Authority(auth = {"system:dictType:add"})
    public Result save(@RequestBody TDataDictionaryType tDataDictionaryType, HttpServletRequest request) throws Exception {
        return super.save(tDataDictionaryType, request);
    }

    @Override
    @Authority(auth = {"system:dictType:update"})
    public Result update(@RequestBody TDataDictionaryType tDataDictionaryType, HttpServletRequest request) throws Exception {
        return super.update(tDataDictionaryType, request);
    }

    @Override
    @Authority(auth = {"system:dictType:delete"})
    public Result delete(String id) {
        try {
            TDataDictionaryType t = baseIService.getById(id);
            if (t==null) {
                return new Result().setMsg("删除失败，实例不存在");
            }
            boolean remove = baseIService.removeById(id);
            return new Result().setSuccess(remove);
        }catch (Exception e){
            log.error("删除失败",e.getMessage());
            return new Result().setMsg("删除失败，请先删除完数据字典明细");
        }
    }

    /**
     * 更新前检查参数
     * @param tDataDictionaryType
     */
    @Override
    public void beforeUpdate(TDataDictionaryType tDataDictionaryType) {
        //判断修改的角色是否存在
        TDataDictionaryType type = service.getOne(new QueryWrapper<TDataDictionaryType>().eq(DataDictionaryTypeConstant.id, tDataDictionaryType.getId()));
        if (type==null) {
            throw  new RuntimeException("类别"+tDataDictionaryType.getName()+"不存在");
        }
        int count = service.count(new QueryWrapper<TDataDictionaryType>()
                .ne(PermissionConstant.id,tDataDictionaryType.getId())
                .nested(query->query
                            .eq(DataDictionaryTypeConstant.name,tDataDictionaryType.getName())
                            .or()
                            .eq(PermissionConstant.code,tDataDictionaryType.getCode())));
        if (count!=0){
            throw  new RuntimeException("类别代码或者名称重复");
        }
    }

    /**
     * 保存前检查参数
     * @param tDataDictionaryType
     */
    @Override
    public void beforeSave(TDataDictionaryType tDataDictionaryType) throws Exception {
        TDataDictionaryType type = service.getOne(new QueryWrapper<TDataDictionaryType>().eq(DataDictionaryTypeConstant.name,tDataDictionaryType.getName()));
        if (type!=null) {
            throw new RuntimeException("类别名称已经存在");
        }
    }
}
